import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { autoUpdater } from 'electron-updater'
import log from 'electron-log'

// 配置日志
log.transports.file.level = 'info'
autoUpdater.logger = log

// 更新检查间隔时间（毫秒）
const UPDATE_CHECK_INTERVAL = 60 * 60 * 1000 // 1小时

function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1100,
    height: 800,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  // 始终打开调试台
  mainWindow.webContents.openDevTools()

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    // mainWindow.loadURL('https://dev.web.qiuyouchat.com/')
    mainWindow.loadURL('http://192.168.31.63:5173/')
    // mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadURL('http://192.168.31.63:5173/')
    mainWindow.loadURL('http://dev.web.qiuyouchat.com/')
    // mainWindow.loadURL('https://web.qiuyouchat.com/')
    // mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// 检查更新函数
function checkForUpdates(): void {
  autoUpdater.checkForUpdates().catch(err => {
    log.error('检查更新失败:', err)
  })
}

// 定时检查更新
function startUpdateChecker(): void {
  setInterval(() => {
    checkForUpdates()
  }, UPDATE_CHECK_INTERVAL)
}

// 发送更新信息到渲染进程
function sendStatusToWindow(text: string, data?: any): void {
  const mainWindow = BrowserWindow.getAllWindows()[0]
  if (mainWindow) {
    mainWindow.webContents.send('update-message', text, data)
  }
}

// 自动更新事件处理
autoUpdater.on('checking-for-update', () => {
  sendStatusToWindow('checking-for-update')
})

autoUpdater.on('update-available', (info) => {
  sendStatusToWindow('update-available', info)
})

autoUpdater.on('update-not-available', (info) => {
  sendStatusToWindow('update-not-available', info)
})

autoUpdater.on('error', (err) => {
  sendStatusToWindow('error', err)
})

autoUpdater.on('download-progress', (progressObj) => {
  sendStatusToWindow('download-progress', progressObj)
})

autoUpdater.on('update-downloaded', (info) => {
  sendStatusToWindow('update-downloaded', info)
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
    // 为所有新创建的窗口打开调试工具
    window.webContents.openDevTools()
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  // 监听渲染进程的更新检查请求
  ipcMain.on('check-for-updates', () => {
    checkForUpdates()
  })

  // 监听渲染进程的重启应用请求
  ipcMain.on('quit-and-install', () => {
    autoUpdater.quitAndInstall()
  })

  createWindow()

  // 启动定时检查更新
  startUpdateChecker()

  // 立即检查一次更新
  setTimeout(() => {
    checkForUpdates()
  }, 5000) // 延迟5秒检查第一次更新

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
